package com.dxy.netty.groupchat;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.util.Scanner;

/**
 * @Description netty群聊客户端
 * @Author dangxianyue
 * @Date 2023/1/6 10:59
 */
public class NettyGroupChatClient {

    /** 主机和端口 */
    private final String host;
    private final int port;

    /**
     * @description 构造器
     * @author xiao tang
     * @date 2022/9/3
     */
    public NettyGroupChatClient(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public static void main(String[] args) {
        try {
            new NettyGroupChatClient("127.0.0.1", 8089).run();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void run() throws InterruptedException {
        // 事件运行的线程池
        EventLoopGroup eventExecutors = new NioEventLoopGroup();
        try {
            // 客户端启动引导对象
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(eventExecutors)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            // 添加解码器 编码器
                            pipeline.addLast("decoder", new StringDecoder());
                            pipeline.addLast("encoder", new StringEncoder());
                            // 添加业务逻辑的 handler
                            pipeline.addLast(new NettyGroupChatClientHandler());
                        }
                    });
            //  连接给定主机的端口，阻塞直到连接成功
            ChannelFuture channelFuture = bootstrap.connect(host, port).sync();
            // 得到 channel
            Channel channel = channelFuture.channel();
            System.out.println("----------" + channel.localAddress() + "----------");
            // 客户端需要输入信息，创建一个扫描器
            Scanner scanner = new Scanner(System.in);
            while (scanner.hasNextLine()) {
                String msg = scanner.nextLine();
                if ("EXIT".equalsIgnoreCase(msg)) {
                    break;
                }
                // 通过channel 发送到服务器
                channel.writeAndFlush(msg);
            }
        } finally {
            // 关闭线程池，释放所有资源，阻塞直到关闭成功
            eventExecutors.shutdownGracefully().sync();
        }

    }
}
